// src/components/popups/scholarOverview/batchUpdateITE/BatchUpdateITEModal.tsx

import React, { useEffect, useState, useCallback, useMemo } from 'react';
import ReactDOM from 'react-dom';
import { fetchScholarBatchUpdate } from '@/services/scholarsDashboardService/fetchScholarBatchUpdate';
import { batchUpdateScholars } from '@/services/scholarsDashboardService/scholarBatchUpdate';
import Pagination from '@/components/scholarDashboard/mainContent/Pagination';

const yesNoOptions = [
  { value: '', label: '-' },
  { value: 'YES', label: 'YES' },
  { value: 'NO', label: 'NO' },
];

const selectClass =
  'w-28 px-2 py-1 border rounded focus:ring-2 focus:ring-blue-400 dark:focus:ring-cyan-700 focus:border-blue-400 dark:focus:border-cyan-700 transition text-xs sm:text-sm md:text-base bg-white dark:bg-slate-800 text-gray-800 dark:text-gray-100 border-gray-300 dark:border-slate-700';
const dateClass =
  'w-32 px-2 py-1 border rounded focus:ring-2 focus:ring-blue-400 dark:focus:ring-cyan-700 focus:border-blue-400 dark:focus:border-cyan-700 transition text-xs sm:text-sm md:text-base bg-white dark:bg-slate-800 text-gray-800 dark:text-gray-100 border-gray-300 dark:border-slate-700';
const inputClass =
  'w-32 px-1 py-1 border rounded focus:ring-2 focus:ring-blue-400 dark:focus:ring-cyan-700 focus:border-blue-400 dark:focus:border-cyan-700 transition text-xs sm:text-sm md:text-base bg-white dark:bg-slate-800 text-gray-800 dark:text-gray-100 border-gray-300 dark:border-slate-700';

const formatDateForDisplay = (dateString: string | null): string => {
  if (!dateString) return '';
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return '';
    return date.toLocaleDateString('en-GB', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric'
    });
  } catch {
    return '';
  }
};

const formatDateForInput = (date: Date | undefined): string => {
  if (!date) return '';
  return date.toISOString().slice(0, 10);
};

interface BatchUpdateITEModalProps {
  onClose: () => void;
}

interface ITEDashboardManualRecord {
  ite_id: number;
  indigenous_student: string | null;
  placement_performance: string | null;
  grade_updated: string | null;
  grade_updated_date: string | null;
  unsw_attendee_presentation: string | null;
  mpc_submitted_date: string | null;
  mpc_submitted_on_time: string | null;
  mpc_call_date: string | null;
  mpc_call_on_time: string | null;
  it_change_approved: string | null;
  first_name: string | null;
  last_name: string | null;
  preferred_name: string | null;
  gender: string | null;
}

interface ITEDashboardManualUpdate {
  ite_id: number;
  indigenous_student?: string;
  placement_performance?: string;
  grade_updated?: string;
  grade_updated_date?: Date;
  unsw_attendee_presentation?: string;
  mpc_submitted_date?: Date;
  mpc_submitted_on_time?: string;
  mpc_call_date?: Date;
  mpc_call_on_time?: string;
  it_change_approved?: string;
}

const itemsPerPage = 10;

const BatchUpdateITEModal: React.FC<BatchUpdateITEModalProps> = ({ onClose }) => {
  const [allRecords, setAllRecords] = useState<ITEDashboardManualRecord[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [loadingProgress, setLoadingProgress] = useState('');
  const [editMode, setEditMode] = useState(false);
  const [editedRows, setEditedRows] = useState<ITEDashboardManualUpdate[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchAllData = useCallback(async () => {
    setLoading(true);
    setError(null);
    setLoadingProgress('');

    try {
      const allResults: ITEDashboardManualRecord[] = [];
      let currentPage = 1;
      let hasMoreData = true;
      const pageSize = 100;

      while (hasMoreData) {
        setLoadingProgress(`Fetching...`);

        const response = await fetchScholarBatchUpdate({
          skip: (currentPage - 1) * pageSize,
          limit: pageSize
        });

        if (!response || !response.records) {
          throw new Error('Invalid response format');
        }

        const records = response.records || [];
        allResults.push(...records);

        const total = response.total || 0;
        const totalPages = Math.ceil(total / pageSize);

        if (currentPage >= totalPages || records.length === 0) {
          hasMoreData = false;
        } else {
          currentPage++;
        }
      }

      setTimeout(() => {
        setAllRecords(allResults);
        setLoading(false);
        setLoadingProgress('');
      }, 300);
    } catch (e: unknown) {
      const errorMessage = e instanceof Error ? e.message : 'Failed to fetch data';
      setError(errorMessage);
      setAllRecords([]);
      setLoading(false);
      setLoadingProgress('');
    }
  }, []);

  useEffect(() => {
    fetchAllData();
  }, [fetchAllData]);

  const paginatedRecords = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    return allRecords.slice(startIndex, endIndex);
  }, [allRecords, currentPage]);

  const handleEdit = () => {
    setEditedRows(
      paginatedRecords.map(r => ({
        ite_id: r.ite_id,
        indigenous_student: r.indigenous_student ?? '',
        placement_performance: r.placement_performance ?? '',
        grade_updated: r.grade_updated ?? '',
        grade_updated_date: r.grade_updated_date ? new Date(r.grade_updated_date) : undefined,
        unsw_attendee_presentation: r.unsw_attendee_presentation ?? '',
        mpc_submitted_date: r.mpc_submitted_date ? new Date(r.mpc_submitted_date) : undefined,
        mpc_submitted_on_time: r.mpc_submitted_on_time ?? '',
        mpc_call_date: r.mpc_call_date ? new Date(r.mpc_call_date) : undefined,
        mpc_call_on_time: r.mpc_call_on_time ?? '',
        it_change_approved: r.it_change_approved ?? '',
      }))
    );
    setEditMode(true);
  };

  const handleCancel = () => {
    setEditMode(false);
    setEditedRows([]);
  };

  const handleChange = (idx: number, key: keyof ITEDashboardManualUpdate, value: string) => {
    setEditedRows(prev => prev.map((row, i) => {
      if (i === idx) {
        const updatedRow = { ...row };
        if (key === 'grade_updated_date' || key === 'mpc_submitted_date' || key === 'mpc_call_date') {
          (updatedRow as ITEDashboardManualUpdate)[key] = value ? new Date(value) : undefined;
        } else {
          (updatedRow as Record<keyof ITEDashboardManualUpdate, unknown>)[key] = value;
        }
        return updatedRow;
      }
      return row;
    }));
  };

  const handleSave = async () => {
    setSubmitting(true);
    setError(null);
    try {
      const updates = editedRows.map(row => ({
        ...row,
        ite_id: Number(row.ite_id),
      }));
      await batchUpdateScholars(updates);
      setEditMode(false);
      setEditedRows([]);
      await fetchAllData();
    } catch (e: unknown) {
      const errorMessage = e instanceof Error ? e.message : 'Batch update failed';
      setError(errorMessage);
    } finally {
      setSubmitting(false);
    }
  };

  const renderTableHead = () => (
    <thead className="bg-blue-50 dark:bg-slate-800 border-b-2 border-gray-200 dark:border-slate-700 shadow-sm">
      <tr>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">ITE ID*</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">First Name</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">Last Name</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">Preferred Name</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">Gender</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">Indigenous Student</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">Placement Performance</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">Grade Updated</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">Grade Updated Date</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">UNSW Attendee on Presentation</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">MPC Submitted Date</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">MPC Submitted On Time</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">MPC Call Date</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">MPC Call On Time</th>
        <th className="px-2 py-2 whitespace-nowrap text-gray-700 dark:text-cyan-300 font-bold">IT Change Approved</th>
      </tr>
    </thead>
  );

  const renderTableBody = () => {
    if (editMode) {
      return (
        <tbody>
          {editedRows.map((row, idx) => (
            <tr key={row.ite_id} className="border-b border-gray-100">
              <td className="px-2 py-1 whitespace-nowrap">{row.ite_id}</td>
              {/* Scholar information fields - Read only */}
              <td className="px-2 py-1 whitespace-nowrap bg-gray-50 dark:bg-slate-700 text-gray-600 dark:text-gray-300">{paginatedRecords[idx]?.first_name ?? ''}</td>
              <td className="px-2 py-1 whitespace-nowrap bg-gray-50 dark:bg-slate-700 text-gray-600 dark:text-gray-300">{paginatedRecords[idx]?.last_name ?? ''}</td>
              <td className="px-2 py-1 whitespace-nowrap bg-gray-50 dark:bg-slate-700 text-gray-600 dark:text-gray-300">{paginatedRecords[idx]?.preferred_name ?? ''}</td>
              <td className="px-2 py-1 whitespace-nowrap bg-gray-50 dark:bg-slate-700 text-gray-600 dark:text-gray-300">{paginatedRecords[idx]?.gender ?? ''}</td>
              {/* Indigenous Student - YES/NO */}
              <td className="px-2 py-1 whitespace-nowrap">
                <select
                  className={selectClass}
                  value={row.indigenous_student || ''}
                  onChange={e => handleChange(idx, 'indigenous_student', e.target.value)}
                >
                  {yesNoOptions.map(opt => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </td>
              {/* Placement Performance - text */}
              <td className="px-2 py-1 whitespace-nowrap">
                <input className={inputClass} value={row.placement_performance} onChange={e => handleChange(idx, 'placement_performance', e.target.value)} />
              </td>
              {/* Grade Updated - YES/NO */}
              <td className="px-2 py-1 whitespace-nowrap">
                <select
                  className={selectClass}
                  value={row.grade_updated || ''}
                  onChange={e => handleChange(idx, 'grade_updated', e.target.value)}
                >
                  {yesNoOptions.map(opt => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </td>
              {/* Grade Updated Date - date */}
              <td className="px-2 py-1 whitespace-nowrap">
                <input
                  type="date"
                  className={dateClass}
                  value={row.grade_updated_date ? formatDateForInput(row.grade_updated_date) : ''}
                  onChange={e => handleChange(idx, 'grade_updated_date', e.target.value)}
                />
              </td>
              {/* UNSW Attendee Presentation - YES/NO */}
              <td className="px-2 py-1 whitespace-nowrap">
                <select
                  className={selectClass}
                  value={row.unsw_attendee_presentation || ''}
                  onChange={e => handleChange(idx, 'unsw_attendee_presentation', e.target.value)}
                >
                  {yesNoOptions.map(opt => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </td>
              {/* MPC Submitted Date - date */}
              <td className="px-2 py-1 whitespace-nowrap">
                <input
                  type="date"
                  className={dateClass}
                  value={row.mpc_submitted_date ? formatDateForInput(row.mpc_submitted_date) : ''}
                  onChange={e => handleChange(idx, 'mpc_submitted_date', e.target.value)}
                />
              </td>
              {/* MPC Submitted On Time - YES/NO */}
              <td className="px-2 py-1 whitespace-nowrap">
                <select
                  className={selectClass}
                  value={row.mpc_submitted_on_time || ''}
                  onChange={e => handleChange(idx, 'mpc_submitted_on_time', e.target.value)}
                >
                  {yesNoOptions.map(opt => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </td>
              {/* MPC Call Date - date */}
              <td className="px-2 py-1 whitespace-nowrap">
                <input
                  type="date"
                  className={dateClass}
                  value={row.mpc_call_date ? formatDateForInput(row.mpc_call_date) : ''}
                  onChange={e => handleChange(idx, 'mpc_call_date', e.target.value)}
                />
              </td>
              {/* MPC Call On Time - YES/NO */}
              <td className="px-2 py-1 whitespace-nowrap">
                <select
                  className={selectClass}
                  value={row.mpc_call_on_time || ''}
                  onChange={e => handleChange(idx, 'mpc_call_on_time', e.target.value)}
                >
                  {yesNoOptions.map(opt => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </td>
              {/* IT Change Approved - YES/NO */}
              <td className="px-2 py-1 whitespace-nowrap">
                <select
                  className={selectClass}
                  value={row.it_change_approved || ''}
                  onChange={e => handleChange(idx, 'it_change_approved', e.target.value)}
                >
                  {yesNoOptions.map(opt => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </td>
            </tr>
          ))}
        </tbody>
      );
    } else {
      return (
        <tbody>
          {allRecords.length === 0 ? (
            <tr>
              <td colSpan={15} className="text-center py-6 text-gray-400 italic bg-gray-50 rounded-b-2xl">
                No records found.
              </td>
            </tr>
          ) : (
            paginatedRecords.map((row) => (
              <tr key={row.ite_id} className="border-b border-gray-100">
                <td className="px-2 py-1 whitespace-nowrap">{row.ite_id}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.first_name ?? ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.last_name ?? ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.preferred_name ?? ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.gender ?? ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.indigenous_student ?? ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.placement_performance ?? ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.grade_updated ?? ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.grade_updated_date ? formatDateForDisplay(row.grade_updated_date) : ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.unsw_attendee_presentation ?? ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.mpc_submitted_date ? formatDateForDisplay(row.mpc_submitted_date) : ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.mpc_submitted_on_time ?? ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.mpc_call_date ? formatDateForDisplay(row.mpc_call_date) : ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.mpc_call_on_time ?? ''}</td>
                <td className="px-2 py-1 whitespace-nowrap">{row.it_change_approved ?? ''}</td>
              </tr>
            ))
          )}
        </tbody>
      );
    }
  };

  const modalContent = (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 dark:bg-black/80 backdrop-blur-sm p-2 sm:p-4 font-poppins text-xs sm:text-sm md:text-base"
      onClick={onClose}
    >
      <div
        className="w-full max-w-5xl bg-white dark:bg-slate-900 rounded-2xl shadow-2xl dark:shadow-blue-900 overflow-hidden animate-fade-in-up max-h-[90vh] overflow-y-auto relative border border-gray-200 dark:border-slate-800"
        onClick={e => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 sm:px-6 py-4 sm:py-5 bg-white dark:bg-slate-900 text-gray-800 dark:text-cyan-200 flex justify-between items-center border-b border-gray-200 dark:border-slate-800 rounded-t-2xl shadow-sm text-xs sm:text-sm md:text-base">
          <h2 className="text-base sm:text-lg md:text-2xl font-extrabold tracking-tight break-words text-blue-700 dark:text-cyan-300">
            Batch Update ITE Dashboard
          </h2>
          <button
            onClick={onClose}
            className="w-9 h-9 flex items-center justify-center rounded-full text-xl font-bold text-gray-500 dark:text-gray-300 hover:text-red-600 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-900 transition focus:outline-none focus:ring-2 focus:ring-red-300 dark:focus:ring-red-800"
          >
            ×
          </button>
        </div>

        {/* Body */}
        <div className="p-3 sm:p-6 space-y-4 text-xs sm:text-sm md:text-base text-gray-800 dark:text-gray-100 bg-white dark:bg-slate-900">
          {error && <div className="text-red-500 dark:text-red-400 text-center font-semibold mb-2">{error}</div>}
          {loading ? (
            <div className="text-center text-gray-400 dark:text-gray-500 animate-pulse py-8 text-base sm:text-lg">
              {loadingProgress || 'Loading results...'}
            </div>
          ) : (
            <div className="w-full overflow-x-auto mt-2 rounded-2xl shadow bg-white dark:bg-slate-900 border border-gray-200 dark:border-slate-800">
              <table className="min-w-[900px] w-full text-xs sm:text-sm md:text-base rounded-2xl overflow-hidden">
                {renderTableHead()}
                {renderTableBody()}
              </table>
            </div>
          )}
          {allRecords.length > itemsPerPage && (
            <Pagination
              currentPage={currentPage}
              setCurrentPage={setCurrentPage}
              totalCount={allRecords.length}
              pageSize={itemsPerPage}
            />
          )}
          <div className="flex flex-row gap-2 mt-4 justify-end">
            {!editMode ? (
              <button className="px-4 py-2 rounded-lg bg-blue-600 dark:bg-cyan-700 text-white font-semibold hover:bg-blue-700 dark:hover:bg-cyan-800 transition" onClick={handleEdit} disabled={loading || allRecords.length === 0}>Edit Mode</button>
            ) : (
              <>
                <button className="px-4 py-2 rounded-lg bg-green-600 dark:bg-emerald-700 text-white font-semibold hover:bg-green-700 dark:hover:bg-emerald-800 transition" onClick={handleSave} disabled={submitting}>{submitting ? 'Saving...' : 'Save'}</button>
                <button className="px-4 py-2 rounded-lg bg-gray-200 dark:bg-slate-700 text-gray-700 dark:text-gray-200 font-semibold hover:bg-gray-300 dark:hover:bg-slate-600 transition" onClick={handleCancel} disabled={submitting}>Cancel</button>
              </>
            )}
            <button className="px-4 py-2 rounded-lg bg-gray-100 dark:bg-slate-800 text-gray-600 dark:text-gray-200 font-semibold hover:bg-gray-200 dark:hover:bg-slate-700 transition" onClick={onClose} disabled={submitting}>Close</button>
          </div>
        </div>
      </div>
    </div>
  );

  return ReactDOM.createPortal(modalContent, document.body);
};

export default BatchUpdateITEModal; 